#include "unp.h"

ssize_t write_fd(int fd, void* ptr, int nbytes);

int main(int argc, char **argv)
{
  if (argc != 2)
  {
    printf("usage : domainsvr <filepath>\n");
    exit(-1);
  }
  
  int listenfd, connfd;
  int n,i;
  socklen_t clilen;
  char buf[128] = {'\0'};
  struct sockaddr_un cliaddr, servaddr;
  
  listenfd = socket(AF_LOCAL, SOCK_STREAM, 0);
  unlink(argv[1]);
  memset(&servaddr, 0,sizeof(servaddr));
  servaddr.sun_family = AF_LOCAL;
  strcpy(servaddr.sun_path, argv[1]);
   
  bind(listenfd, (struct sockaddr*) &servaddr,sizeof(servaddr));
  listen(listenfd, 5);
  
  while (1)
  {
    clilen = sizeof(cliaddr);
    connfd = accept(listenfd, (struct sockaddr*)(&cliaddr), &clilen);
    if (connfd < 0)
    {
      if (errno == EINTR)
      {
	continue;
      }
      else
      {
	printf("accept error\n");
	exit(-1);
      }
    } 
    snprintf(buf,sizeof(buf),"%s","123456789");
    write_fd(connfd,(void*)buf,strlen(buf));
    close(connfd);
  }  
  
  return 0;
}

ssize_t write_fd(int fd, void* ptr, int nbytes)
{
  struct msghdr msg;
  struct iovec  iov[1];
  int n;
 
  memset(&msg,0,sizeof(msg));
  iov[0].iov_base = ptr;
  iov[0].iov_len = nbytes;
  msg.msg_name        = NULL;
  msg.msg_namelen     = 0;
  msg.msg_iov         = iov;
  msg.msg_iovlen      = 1;

  n = sendmsg(fd, &msg,0);  
 
  return n;
}
